/**
 * 系统用户js
 */
var sysUser= {
	curPage:1,
	pageSize:10,
	dataCache:null,
	selectedUsers: [],

	startEvent:function(){
		//按回车键登录事件
		document.onkeydown = function(e){ 
    		var ev = document.all ? window.event : e;
    		if(ev.keyCode==13) {
    			sysUser.curPage=1;
    			sysUser.setPageChange(null);
    			sysUser.search();
     		}
		};


	},

	getChannelResource : function() {
		var url = 'mgr/userChannelCtrl/list';
		var params = {
			'curPage' : 0,
			'pageSize' : 9999
		};
		var cb = function(data) {
			if (data.resultCode == 200) {
				var option = '<option value="">请选择</option>';
				for (var i = 0; i < data.result.length; i++) {
					var singleObj = data.result[i];
					option = option + '<option value="' + singleObj.channelId + '">'
						+ singleObj.name + '</option>';
				}
				$('select[name="channel"]').append(option);
			}
		};
		sendApiNoLoad(url, params, cb, 'POST');
	},
	 
	
	bindEvent:function(){
		//查询
		$('#searchData').click(function(){
			sysUser.curPage=1;
			sysUser.setPageChange(null);
			sysUser.search();
		});

		$('#regisData').on('click',function(){
			var path=APP_ADDRESS+'mgr/sysMgr/sysUserAdd02.jsp';
			var test=art;
			art.dialog.open(path, {
			    title: '录入渠道用户',
			    width: 600,
			    height:430,
			    ok: function () {
				   var returnStatus=this.iframe.contentWindow.submitForm();
				   if(returnStatus){
					   sysUser.setPageChange(null);
					   sysUser.search();
				   }
				   art.dialog.close();
				   return false;
			    },
			    cancel: true
			});
		});

		$("select[name='pageSize']").change(function() {
			sysUser.pageSize = $('#pageSize').val();
			sysUser.setPageChange(sysUser.curPage);
		});


		$('#orgFullName').on('click',function(){
			var path=APP_ADDRESS+'mgr/sysMgr/sysUserSelectOrg.jsp';
			art.dialog.open(path, {
				title: '选择组织架构',
				width: 600,
				height:430,
				ok: function () {
					var returnStatus=this.iframe.contentWindow.submitForm();

					if(returnStatus){
						var selectOrgFullName = localStorage.getItem("Selected_Org_FullName");
						var selectOrgId = localStorage.getItem("Selected_Org_Id");
						$('#depId').val(selectOrgId);
						$('#orgFullName').val(selectOrgFullName);
						$('#orgFullName').width(textWidth(selectOrgFullName) + 10);
						sysUser.setPageChange(null);
						sysUser.search();
					}else{
						$('#depId').val('');
						$('#orgFullName').val('');
					}
					return returnStatus;
				},
				cancel: true
			});
		});
		$('#addData').on('click',function(){
			var path=APP_ADDRESS+'mgr/sysMgr/sysUserAdd.jsp';
			art.dialog.open(path, {
			    title: '添加系统用户',
			    width: 600,
			    height:430,
			   ok: function () {
				   var returnStatus=this.iframe.contentWindow.submitForm();
				   if(returnStatus){
					   sysUser.setPageChange(null);
					   sysUser.search();
				   }
				   return false;
			    },
			    cancel: true
			});
		});
		$('#importData').on('click',function(){
			
			var path=APP_ADDRESS+'mgr/sysMgr/sysUserImport.jsp';
			art.dialog.open(path, {
			    title: '添加系统用户',
			    width: 600,
			    height:430,
			   ok: function () {
				   var returnStatus=this.iframe.contentWindow.submitForm();
				   if(returnStatus){
					   sysUser.setPageChange(null);
					   sysUser.search();
				   }
				   return false;
			    },
			    cancel: true
			});
		});
		$('#sysUser_121').on('click',function(){
			console.log($('.checkItem'));

			var aa = $('.checkItem');
			var ss = [];
			for (var i = 0; i < aa.length; i++) {

				if (aa[i].checked) {
					var userId =  aa[i].value;
					var user = eval('(' + localStorage.getItem(userId + "_User_Key") + ')');
					if(user.isInside == 1){
						alert("所选的用户中包含理财师，不允许修改推荐码！");
						return false;
					}
					ss.push( aa[i].value);
				}
			}

			if(ss.length == 0){
				alert("请至少选择一个用户！");
				return false;
			}

			art.dialog.data('selectedUsers', ss);
			var path=APP_ADDRESS+'mgr/sysMgr/sysUserMutiUpdateCode.jsp';
			art.dialog.open(path, {
				title: '批量修改推荐码',
				width: 500,
				height:580,
				ok: function () {
					returnStatus=this.iframe.contentWindow.submitForm();
					if(returnStatus == true){
						sysUser.setPageChange(sysUser.curPage);
						sysUser.search(sysUser.curPage);
					}
					return returnStatus;
				},
				cancel: true
			});
		});

		$('#sysUser_122').on('click',function(){
			console.log($('.checkItem'));
			sysUser.selectedUsers.splice(0,sysUser.selectedUsers.length);

			var aa = $('.checkItem');
			var ss = [];
			for (var i = 0; i < aa.length; i++) {
				if (aa[i].checked) {
					ss.push( aa[i].value);
				}
			}

			if(ss.length == 0){
				alert("请至少选择一个用户！");
				return false;
			}
			art.dialog.data('selectedUsers', ss);
			var path=APP_ADDRESS+'mgr/sysMgr/sysUserMutiUpdateOrg.jsp';
			art.dialog.open(path, {
				title: '批量修改组织架构',
				width: 500,
				height:580,
				ok: function () {
					returnStatus=this.iframe.contentWindow.submitForm();
					if(returnStatus == true){
						sysUser.setPageChange(sysUser.curPage);
						sysUser.search(sysUser.curPage);
					}
					return returnStatus;
				},
				cancel: true
			});
		});
		
		$('#excel').on('click',function () {
			alert("注意：当数据超过1W条时要耐心等待");
			var url = APP_ADDRESS+"/mgr/SysUserCtrl/excel";

            var name = $.trim($('#searchModForm input[name="name"]').val());
            var recommendCode = $.trim($('#searchModForm input[name="recommendCode"]').val());
            var isInside = $.trim($('#searchModForm select[name="isInside"]').val());
            var level = $.trim($('#searchModForm select[name="level"]').val());
            var channel = $.trim($('#searchModForm select[name="channel"]').val());
            var isLeave = $.trim($('#searchModForm select[name="isLeave"]').val());
            var tieCard = $.trim($('#searchModForm select[name="tieCard"]').val());
            var beginDateStr = $.trim($('#beginDate').val());
            var endDateStr = $.trim($('#endDate').val());
            var depId = $.trim($('#searchModForm input[name="depId"]').val());
            var actUserId = userId;

            location.href = url + "?name="+name+"&recommendCode="+recommendCode+"&isInside="+isInside+"&level="+level
			+"&channel="+channel+"&isLeave="+isLeave+"&tieCard="+tieCard+"&beginDateStr="+beginDateStr+"&endDateStr="+endDateStr
			+"&depId="+depId+"&actUserId="+actUserId;

        })
	},
	
	//设置分页
	setPageChange:function(delCurPage){
		console.log("in setPageChange function");
		var url = 'mgr/SysUserCtrl/getSysUserList';
		var params = jsUtils.serializeJson($('#searchModForm'));
		params.actUserId=userId;
		params.curPage = sysUser.curPage;
		params.pageSize = 999999;

		sysUser.selectedUsers.splice(0,sysUser.selectedUsers.length);

		var cb = function(data) {
			console.dir(data);
			//if (data.resultCode == 200) {
				if (data.size > 0) {
					var totalCount = data.size;
					var pageTotal = (totalCount / sysUser.pageSize > 0) ? Math.ceil(totalCount/ sysUser.pageSize) : 1;
					pageHelper.init(pageTotal,totalCount,sysUser.search,delCurPage);  //翻页事件
				}
			//}

		};
		sendApiNoLoad(url, params, cb, 'POST');
		
	},
	
	//查询系统用户
	search:function(pageIdx){
		console.log("in search function");
		var url = 'mgr/SysUserCtrl/getSysUserList';
		if (typeof(pageIdx) != "undefined"){ 
			sysUser.curPage=pageIdx;
		}

		sysUser.selectedUsers.splice(0,sysUser.selectedUsers.length);

		var params = jsUtils.serializeJson($('#searchModForm'));
		params.actUserId=userId;
		params.curPage = sysUser.curPage;
		params.pageSize = $('#pageSize').val();

		var cb = function(data) {
			if (data.resultCode == 200) {
				$('#tableList tbody').empty();
				var tr='';
				 
				if(data.result!=null&&data.result.length>0){
					 
					for(var i=0;i<data.result.length;i++){
						var singleObj=data.result[i];
						
						var registCts = getSmpFormatDateByLong(singleObj.registCts,
								true);


						var orgName = singleObj.orgName;
						if(singleObj.isInside == 0||singleObj.orgName==null){
							orgName = "";
						}

						localStorage.setItem(singleObj.id + "_User_Key", JSON.stringify(singleObj));

						tr += '<tr class="row" ><td class="col-md-1">'
								+ '<input type="hidden" name="kycPdfUrl" value="' + singleObj.kycPdfUrl +'"/>'
                            	+ '<input type="hidden" name="ifaPdfUrl" value="' + singleObj.ifaUrl +'"/>'
								+ '<input type="checkbox" name ="checkItem" style="margin-right: 10px;" value="' + singleObj.id + '"  class="checkItem"/>'
								+ '<input type="hidden" name="id" value="'+singleObj.id+'"/>'
								+ (i+1)
								+ '</td><td class="col-md-1">'
								+ singleObj.name
								+ '</td><td class="col-md-1">'
								+  (singleObj.realName==null?'':singleObj.realName)
								+ '</td><td class="col-md-1">'
								+  singleObj.channelName
								+ '</td><td class="col-md-1">'
								+  (singleObj.orgDepName==null?'':singleObj.orgDepName)
								+ '</td><td class="col-md-1"">'
								+  orgName
								+ '</td><td class="col-md-1">'
								+ registCts
								+ '</td><td class="col-md-1">'
								+ (singleObj.isInside==1?"是":"否")
								+ '</td><td class="col-md-1">'
								+ (singleObj.isInside==1?(singleObj.onType== 1 ? "离职":"在职"):"客户")
								+ '</td><td class="col-md-1">'
								+ singleObj.scoreDesc
								+ '</td><td class="col-md-1">'
								+ singleObj.scoreCts
								+ '</td><td class="col-md-3">'
								+'<a type="button" name="sysUser_99" class="btn btn-primary btn-xs lookData" style="margin-left: 5px; margin-top: 10px; display:none;">'
								+'<i class="fa fa-reorder"></i> 查看 </a>'
								+'<a type="button" name="sysUser_96" class="btn btn-success btn-xs updateData" style="margin-left: 5px; margin-top: 10px; display:none;">'
								+'<i class="fa fa-edit"></i>修改</a>'
								+'<a type="button" name="sysUser_95" class="btn btn-default btn-xs initData" style="margin-left: 5px; margin-top: 10px; display:none;">'
								+'<i class="fa fa-minus-square-o"></i> 初始化密码</a>'
								+'<a type="button" name="sysUser_103" class="btn btn-default btn-xs updUserCode" style="margin-left: 5px; margin-top: 10px; display:none;">'
								+'<i class="fa fa-minus-square-o"></i> 修改推荐码</a>'
								+'<a type="button" name="sysUser_108" class="btn btn-default btn-xs addCard" style="margin-left: 5px; margin-top: 10px; display:none;">'
								+'<i class="fa fa-minus-square-o"></i>赠送加息券</a>'
								+'<a type="button" name="sysUser_124" class="btn btn-default btn-xs kycPdfUrl" style="margin-left: 5px; margin-top: 10px; display:none;">'
								+'<i class="fa fa-minus-square-o"></i>投资测评</a>'
								+'<a type="button" name="sysUser_254" class="btn btn-default btn-xs ifaPdfUrl" style="margin-left: 5px; margin-top: 10px; display:none;">'
								+'<i class="fa fa-minus-square-o"></i>ifa协议</a>'
								+'<a type="button" name="sysUser_255" class="btn btn-default btn-xs closeAccount" style="margin-left: 5px; margin-top: 10px; display:none;">'
								+'<i class="fa fa-minus-square-o"></i>销户</a>'
								+'</td></div></tr>';
					}
				}
				$('#tableList tbody').html(tr);
				sysUser.bindEventOtherBtn();
				jsUtils.controlFunctionBtn();
			}else{
				alert(data.msg);
				tr='<tr><td colspan="9" style="text-align: center;color: red;">暂无数据</td></tr>';
				$('#tableList tbody').html(tr);
			}
		};
		sendApiNoLoad(url, params, cb, 'POST');
	},
	
	bindEventOtherBtn:function(){
		$('.initData').unbind();
		$('.initData').on('click',function(){
			var thisObj=$(this);
			art.dialog.confirm('你确认初始化？', function(){
				var id=thisObj.parent().parent().find('input[name="id"]').eq(0).val();
				var url = 'mgr/SysUserCtrl/initSysUserPwd';
				var params = {
						'id':id
				};
				var cb = function(data){
					alert(data.msg);
					sysUser.setPageChange(sysUser.curPage);
					sysUser.search(sysUser.curPage);
				}
				sendApiNoLoad(url, params, cb, 'POST');
			}, function(){
			});
		});
		$('.deleteData').unbind();
		$('.deleteData').on('click',function(){
			var thisObj=$(this);
			art.dialog.confirm('你确认删除？', function(){
				var id=thisObj.parent().parent().find('input[name="id"]').eq(0).val();
				var url = 'mgr/SysUserCtrl/deleteSysUser';
				var params = {
						'id':id
				};
				var cb = function(data){
					alert('删除成功！');
					sysUser.setPageChange(sysUser.curPage);
					sysUser.search(sysUser.curPage);
				}
				sendApiNoLoad(url, params, cb, 'POST');
			}, function(){
			});
		});
		$('.updUserCode').unbind();
		$('.updUserCode').on('click',function(){
			var thisObj=$(this);
			var id=thisObj.parent().parent().find('input[name="id"]').eq(0).val();
			art.dialog.data('updId', id);
			var path=APP_ADDRESS+'mgr/sysMgr/sysUserUpdateCode.jsp';
			var returnStatus = false;
			var dialog = art.dialog.open(path, {
			    title: '修改用户推荐码',
			    width: 500,
			    height:150,
			   ok: function () {
				    returnStatus=this.iframe.contentWindow.submitForm();
				   if(returnStatus){
					   dialog.close()
					   sysUser.setPageChange(sysUser.curPage);
					   sysUser.search(sysUser.curPage);
				   }
			    },
			    cancel: true
			});
		});
		$('.addCard').unbind();
		$('.addCard').on('click',function(){
			var thisObj=$(this);
			art.dialog.confirm('你确认赠送加息券？', function(){
				var id=thisObj.parent().parent().find('input[name="id"]').eq(0).val();
				var url = 'mgr/SysUserCtrl/addCard';
				var params = {
					'userId':id
				};
				var cb = function(data){
					alert(data.msg);
					sysUser.setPageChange(sysUser.curPage);
					sysUser.search(sysUser.curPage);
				}
				sendApiNoLoad(url, params, cb, 'POST');
			}, function(){
			});
		});

		$('.kycPdfUrl').unbind();
		$('.kycPdfUrl').on('click', function() {
			console.log('hello world');

			var thisObj = $(this);

			console.log(thisObj);

			var url = thisObj.parent().parent().find('input[name="kycPdfUrl"]').eq(0).val();

			console.log(url);

			if(url != null && url != '' && url !="null"){
				if (url.indexOf("null") == -1) {
					window.open(url);
				} else {
					alert("风险测评未生成！");
				}
			}else{
				alert("该用户还未做风险测评！");
			}
		});

		// ifaPdfUrl
        $('.ifaPdfUrl').unbind();
        $('.ifaPdfUrl').on('click', function() {
            console.log('hello world');

            var thisObj = $(this);

            console.log(thisObj);

            var url = thisObj.parent().parent().find('input[name="ifaPdfUrl"]').eq(0).val();

            console.log(url);

            if(url != null && url != '' && url !="null"){
                if (url.indexOf("null") == -1) {
                    window.open(url);
                } else {
                    alert("ifa协议未生成！");
                }
            }else{
                alert("该用户还未签署ifa协议！");
            }
        });

		$('.updateData').unbind();
		$('.updateData').on('click',function(){
			var thisObj=$(this);
			var id=thisObj.parent().parent().find('input[name="id"]').eq(0).val();
			art.dialog.data('updId', id);
			var path=APP_ADDRESS+'mgr/sysMgr/sysUserUpdate.jsp';
			var updReturnStatus = false;
			var dialog = art.dialog.open(path, {
			    title: '修改系统用户',
			    width: 600,
			    height:500,
			   ok: function () {
				   updReturnStatus=this.iframe.contentWindow.submitForm();
				   if(updReturnStatus){
					   dialog.close();
					   sysUser.setPageChange(sysUser.curPage);
					   sysUser.search(sysUser.curPage);
					   sendCouponForIFA();
					   resetUserForIFALeave();
				   }

                   return false;
			    },
			    cancel: true
			});
		});
		$('.lookData').unbind();
		$('.lookData').on('click',function(){
			var thisObj=$(this);
			var id=thisObj.parent().parent().find('input[name="id"]').eq(0).val();
			art.dialog.data('lokId', id);
			var path=APP_ADDRESS+'mgr/sysMgr/sysUserLook.jsp';
			art.dialog.open(path, {
			    title: '查看系统用户',
			    width: 500,
			    height:580,
			    cancel: true
			});
		});
        $('.closeAccount').unbind();
        $('.closeAccount').on('click',function(){
            var thisObj=$(this);
            var id=thisObj.parent().parent().find('input[name="id"]').eq(0).val();
            art.dialog.data('closeAccountId', id);
            var path=APP_ADDRESS+'mgr/sysMgr/closeAccount.jsp';
            var closeAccountStatus = false;
            var dialog = art.dialog.open(path, {
                title: '销户',
                width: 500,
                height:200,
				ok:function () {
                	closeAccountStatus = this.iframe.contentWindow.submitForm();
                    if(closeAccountStatus){
                        dialog.close();
                        sysUser.setPageChange(sysUser.curPage);
                        sysUser.search(sysUser.curPage);
                    }


                	return false;
                },
                cancel: true
            });
        });

		$('#checkAll').unbind();
		$('#checkAll').on('click',function(){
			if($("#checkAll").prop("checked")){
				$(".checkItem").prop("checked", 'true');
			}else{
				$(".checkItem").removeAttr("checked");
				sysUser.selectedUsers.splice(0,sysUser.selectedUsers.length);
			}

		});
	},
		
	init : function() {
		sysUser.setPageChange(null);
		sysUser.search();
		sysUser.startEvent();
		sysUser.bindEvent();
		sysUser.getChannelResource();
		jsUtils.controlFunctionBtn();
	}
};

$(document).ready(function() {
	sysUser.init();
});

//提供给外部刷新调用
function refashData(){
	sysUser.setPageChange(null);
	//sysUser.search();
}

function sendCouponForIFA() {
    var financialId = art.dialog.data('updId');

    var updateIFAtrace = art.dialog.data('updateIFAtrace');

    //only become IFS from 0 to 1 able to send coupon
    if(updateIFAtrace != '01')
        return;

    var url = "app/financial/checkIFA/" + financialId;

    var callback = function(data){

        if (data.resultCode != '200') {
            layer.msg(data.result);
            return;
        }

        var sendHistoryCounter = data.result;
        // only 1st time become IFA
        if(sendHistoryCounter > 0)
            return;

        //询问框
        layer.confirm('用户信息编辑成功，是否赠送该用户及推荐码为该用户手机号码的客户新有主客户加息券？？', {
            title:'赠送加息券',
            btn: ['不赠送', '确定赠送'] //按钮
        }, function () {
            cancelSendCoupon();
        }, function () {
            sendCoupon()
        });

    };
    sendApiNoLoadSync(url, null, callback, 'GET');
}

function resetUserForIFALeave(){
    var financialId = art.dialog.data('updId');

    var updateIFAtrace = art.dialog.data('updateIFAtrace');

    //only when IFS leave, from 1 to 0 able to reset user
    if(updateIFAtrace != '10')
        return;

    var url = "mgr/SysUserCtrl/multiUpdateOrgForFinancialLeave";

    var params = {
        'financialId':financialId,
        'operatorId':userId
    };


   // 询问框
    layer.confirm('用户信息编辑成功，是否将推荐码为该理财师的客户所属部门修改为最近的无主客户部？', {
        title: '客户组织架构修改',
        btn: ['不修改', '确定修改'] //按钮
    }, function () {
        layer.msg('已取消修改');
    }, function () {
        var index = layer.load(0, {shade: false, offset: '600px'});

        var callback = function (data) {
            layer.close(index);

            if (data.resultCode != '1') {
                layer.msg(data.result);
                return;
            }

            layer.msg(data.msg+' 受影响记录: '+data.size);
        };


        sendApiNoLoadSync(url, params, callback, 'POST');
    });

}

function cancelSendCoupon() {
    var financialId = art.dialog.data('updId');
    console.log('financialId : ' + financialId+' cancelSendCoupon');

    var url = "app/financial/cancelSendCoupon/" + financialId;

    var callback = function(data){
        console.log(JSON.stringify(data));

        if (data.resultCode != '200') {
            layer.msg(data.result);
            return;
        }

        layer.msg('不赠送', {icon: 1});
    };
    sendApiNoLoadSync(url, null, callback, 'POST');
}

function sendCoupon() {
    var financialId = art.dialog.data('updId');
    console.log('financialId : ' + financialId+' sendCoupon');

    var url = "app/financial/sendCoupon/" + financialId;

    var callback = function (data) {
        console.log(JSON.stringify(data));

        if (data.resultCode != '200') {
            layer.msg(data.result);
            return;
        }
        var totalSuccessNum = data.result.totalSuccessNum;

        layer.msg('已成功赠送'+totalSuccessNum+'张', {icon: 1});
    };
    sendApiNoLoadSync(url, null, callback, 'POST');
}

function textWidth(text){
	var sensor = $('<pre>'+ text +'</pre>').css({display: 'none'});
	$('body').append(sensor);
	var width = sensor.width();
	sensor.remove();
	return width;
};


